/**
 * 
 */
package org.compiere.model;

import java.awt.Container;
import java.io.File;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;

import javax.swing.JFrame;

import org.compiere.apps.IProcessParameter;
import org.compiere.apps.ProcessCtl;
import org.compiere.apps.ProcessParameterPanel;
import org.compiere.apps.Waiting;
import org.compiere.process.DocAction;
import org.compiere.process.DocumentEngine;
import org.compiere.process.ProcessInfo;
import org.compiere.process.ProcessInfoParameter;
import org.compiere.util.ASyncProcess;
import org.compiere.util.CCache;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.Env;
import org.compiere.util.Msg;

import extend.org.compiere.callout.CalloutInterCheckOff;
import extend.org.compiere.utils.Util;

/**
 * @author A.Yerzhanov
 * 21.11.2012
 */
public class Mhrmintercheckoff extends X_hrm_intercheckoff implements DocAction, ASyncProcess {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 2721187127435231810L;

	/**	Static Logger	*/
	private static CLogger	s_log	= CLogger.getCLogger (Mhrmintercheckoff.class);
	
	private int AD_Process_ID;
	
	/**/
	ASyncProcess m_parent;	

	/**
	 * @param ctx
	 * @param hrm_intercheckoff_ID
	 * @param trxName
	 */
	public Mhrmintercheckoff(Properties ctx, int hrm_intercheckoff_ID,
			String trxName) {
		super(ctx, hrm_intercheckoff_ID, trxName);
		
		if(hrm_intercheckoff_ID == 0){
			setDocStatus (DOCSTATUS_Drafted);		//	Draft
			setDocAction (DOCACTION_Complete);
			setC_DocType_ID(1000063);
			setIsSOTrx (true);
			setIsApproved (false);
			setIsTransferred (false);
			setC_Currency_ID(341);			
			setPosted(false);
			super.setProcessed (false);
			setProcessing(false);
		}
	}

	/**
	 * @param ctx
	 * @param rs
	 * @param trxName
	 */
	public Mhrmintercheckoff(Properties ctx, ResultSet rs, String trxName) {
		super(ctx, rs, trxName);
	}

	public static Mhrmintercheckoff getInterRec(int C_BPartner_ID, Timestamp dt){
		//
	    PreparedStatement pstmt = null;
		ResultSet rs = null;
		Mhrmintercheckoff result = null;
			
		// 
		String sql_ = "SELECT * FROM HRM_INTERCHECKOFF \n " +
						"WHERE ISACTIVE='Y' \n "  +
						   " AND AD_CLIENT_ID="  + Env.getAD_Client_ID(Env.getCtx()) + " \n " + 
						   " AND C_BPARTNER_ID=" + C_BPartner_ID   + " \n" +
						   " AND DATEFROM="      + DB.TO_DATE(dt)  + " \n ";
			try
			{
				pstmt = DB.prepareStatement(sql_,null);				
				rs = pstmt.executeQuery();	
				if(rs.next())
					result = new Mhrmintercheckoff(Env.getCtx(), rs, null);
			}
			catch (SQLException e)
			{
				s_log.log(Level.SEVERE, "product", e);
			}
			finally
			{
				DB.close(rs, pstmt);
				rs = null; pstmt = null;
			}
			
		return result;		
	}
	
	
	/**	Intercheckoff Lines	*/
	private Mhrmintercheckoffline[] m_lines;
	private X_hrm_intercheckoffline[] m_linesacct;
	
	/**
	 * 	Get HR Intercheckoff Lines
	 * 	@param whereClause starting with AND
	 * 	@return lines
	 */
	private Mhrmintercheckoffline[] getLinesIntercheckoff (String whereClause)
	{
		String whereClauseFinal = "hrm_intercheckoff_ID=? ";
		if (whereClause != null)
			whereClauseFinal += whereClause;
		List<Mhrmintercheckoffline> list = new Query(getCtx(), I_hrm_intercheckoffline.Table_Name, whereClauseFinal, get_TrxName())
										.setParameters(gethrm_intercheckoff_ID())
										.list();
		return list.toArray(new Mhrmintercheckoffline[list.size()]);
	}	//	getLines

	/**
	 * 	Get Intercheckoff Lines
	 * 	@param requery
	 * 	@return lines
	 */
	public Mhrmintercheckoffline[] getLinesIntercheckoff(boolean requery)
	{
		if (m_lines == null || m_lines.length == 0 || requery)
			m_lines = getLinesIntercheckoff(null);
		set_TrxName(m_lines, get_TrxName());
		return m_lines;
	}	//	getLines

	/**
	 * 	Get intercheckoff line
	 * 	@return lines
	 */
	public Mhrmintercheckoffline[] getLinesIntercheckoff()
	{
		return getLinesIntercheckoff(false);
	}	//	getLines
	
//	 X_hrm_intercheckoffline {
	/**
	 * 	Get HR intercheckoff Lines
	 * 	@param whereClause starting with AND
	 * 	@return lines
	 */
	private X_hrm_intercheckoffline[] getLinesintercheckoffAcct (String whereClause)
	{
		String whereClauseFinal = "hrm_intercheckoff_ID=? ";
		if (whereClause != null)
			whereClauseFinal += whereClause;
		List<X_hrm_intercheckoffline> list = new Query(getCtx(), I_hrm_intercheckoffline.Table_Name, whereClauseFinal, get_TrxName())
										.setParameters(gethrm_intercheckoff_ID())
										.list();
		return list.toArray(new X_hrm_intercheckoffline[list.size()]);
	}	//	getLines

	/**
	 * 	Get intercheckoff Lines
	 * 	@param requery
	 * 	@return lines
	 */
	public X_hrm_intercheckoffline[] getLinesintercheckoffAcct (boolean requery)
	{
		if (m_linesacct == null || m_linesacct.length == 0 || requery)
			m_linesacct = getLinesintercheckoffAcct(null);
		set_TrxName(m_linesacct, get_TrxName());
		return m_linesacct;
	}	//	getLines

	/**
	 * 	Get intercheckoff line
	 * 	@return lines
	 */

	public X_hrm_intercheckoffline[] getLinesintercheckoffAcct()
	{
		return getLinesintercheckoffAcct(false);
	}	//	getLines
	
	public static BigDecimal getAmountType(int C_BPartner_ID, Timestamp dt, String type){
		
		if(C_BPartner_ID == 0)
    		return null;
		
		BigDecimal result = new BigDecimal(0);
		StringBuffer sql = new StringBuffer();		
		
		sql.append("SELECT coalesce(ROUND(SUM(hrm_total),2),0) FROM HRM_INTERCHECKOFF \n");
		sql.append(" WHERE AD_CLIENT_ID=" + Env.getAD_Client_ID(Env.getCtx()) + " \n " +
				   " AND C_BPARTNER_ID=" + C_BPartner_ID + " \n " +
				   " AND DATE_TRUNC('MONTH',DATEFROM) <=" + DB.TO_DATE(dt) + " \n " +
				   " AND DATE_TRUNC('MONTH',DATEFROM) + '1 MON'::INTERVAL - '1 DAY'::INTERVAL >=" + DB.TO_DATE(dt) + " \n " +
				   " AND DOCSTATUS = 'CO' \n" +
				   " AND LOWER(HRM_DEDUCTIONTYPE)=LOWER('"+type+"')");		
		
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try
		{
			pstmt = DB.prepareStatement(sql.toString(),null);						
			rs = pstmt.executeQuery();
			if(rs.next())
				return rs.getBigDecimal(1);		
		}
		catch (SQLException e)
		{
			s_log.log(Level.SEVERE, "product", e);
		}
		finally
		{
			DB.close(rs, pstmt);
			rs = null; pstmt = null;
		}

		return result;
	}
	
	/* 
	 */
	public void setProcessed (boolean processed)
	{
		super.setProcessed (processed);
		if (get_ID() == 0)
			return;
		String set = "SET Processed='"
			+ (processed ? "Y" : "N")
			+ "' WHERE hrm_intercheckoff_ID = " + gethrm_intercheckoff_ID();
		DB.executeUpdate("UPDATE hrm_intercheckoff " + set, get_TrxName());
	}	//	setProcessed

	public String prepareIt() {
		log.info(toString());
		m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_PREPARE);
		if (m_processMsg != null)
			return DocAction.STATUS_Invalid;

		//	Convert/Check DocType
		if (getC_DocType_ID() == 0)
		{
			m_processMsg = "No Document Type";
			return DocAction.STATUS_Invalid;
		}

		m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_AFTER_PREPARE);
		if (m_processMsg != null)
			return DocAction.STATUS_Invalid;

		//	Add up Amounts
		m_justPrepared = true;
		if (!DOCACTION_Complete.equals(getDocAction()))
			setDocAction(DOCACTION_Complete);
		return DocAction.STATUS_InProgress;
	}	

	public boolean processIt (String processAction)
	{
		m_processMsg = null;
		DocumentEngine engine = new DocumentEngine (this, getDocStatus());
		return engine.processIt (processAction, getDocAction());
	}	//	process
	
	/**	Process Message 			*/
	private String		m_processMsg = null;
	/**	Just Prepared Flag			*/
	private boolean		m_justPrepared = false;

	private Waiting m_waiting;
	

	public void lockUI(ProcessInfo pi) {
		JFrame frame = Env.getFrame((Container)m_parent);
		m_waiting = new Waiting (frame, Msg.getMsg(Env.getCtx(), "Processing"), false, pi.getEstSeconds());
		
	}
	
	public void unlockUI(ProcessInfo pi) {

		if (m_waiting != null)
			m_waiting.dispose();
		m_waiting = null;	}

	@Override
	public boolean isUILocked() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void executeASync(ProcessInfo pi) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean unlockIt() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean invalidateIt() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean approveIt() {
		log.info(toString());
		setIsApproved(true);
		return true;
	}
	
	public boolean rejectIt() {
		// TODO Auto-generated method stub
		return false;
	}
	
	protected void getAD_Process_ID() {
		
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		// 
		String sql_ = "select distinct t.ad_process_id from ad_process t \n "+ 
					  "where (lower(t.value) like lower('GenerateIntercheckoff') or lower(t.name) like lower('GenerateIntercheckoff')) "+ 
				      "and t.isactive='Y'";
		try
		{
			pstmt = DB.prepareStatement(sql_, null);
			rs = pstmt.executeQuery();
			if (rs.next())
				AD_Process_ID = rs.getInt(1);
		}
		catch (SQLException e)
		{
			log.log(Level.SEVERE, "product", e);
		}
		finally
		{
			DB.close(rs, pstmt);
			rs = null; pstmt = null;
		}
	}
	
	public String completeIt() {
		getAD_Process_ID();
		
		if(AD_Process_ID != 0){
			//  Prepare Process
			ProcessInfo pi = new ProcessInfo ("The printing process of ", AD_Process_ID);
			pi.setAD_User_ID (Env.getAD_User_ID(Env.getCtx()));
			pi.setAD_Client_ID(Env.getAD_Client_ID(Env.getCtx()));
			pi.setRecord_ID(get_ID());

			List<ProcessInfoParameter> po = new ArrayList<ProcessInfoParameter>();
			po.add(new ProcessInfoParameter("CloseTax","Y",null,"",""));
			//
			ProcessInfoParameter[] pp = new ProcessInfoParameter[po.size()];
			po.toArray(pp);
			pi.setParameter(pp);
			//	Execute Process
			ProcessParameterPanel pu = new ProcessParameterPanel(0, pi);
			ProcessCtl.process(this, 0, (IProcessParameter) pu, pi, null);
		}
		
		//	Re-Check
		if (!m_justPrepared)
		{
			String status = prepareIt();
			if (!DocAction.STATUS_InProgress.equals(status))
				return status;
		}

		m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_COMPLETE);
		if (m_processMsg != null)
			return DocAction.STATUS_Invalid;
//
//		//	Implicit Approval
		if (!isApproved())
			approveIt();
		log.info(toString());
		
		StringBuffer info = new StringBuffer();
		
		m_processMsg = info.toString().trim();
		setProcessed(true);
//		save();
		setDocAction(DOCACTION_Close);
		return DocAction.STATUS_Completed;	
	}
	
	public boolean voidIt() {
		boolean result = true;
		if (!haveCorrectDocument()) {
			if ( DocAction.STATUS_Completed.equals(getDocStatus()) && isPosted()) {
				result = reverseCorrectIt();
			}
			if (result) {
				setProcessed(true);
				setDocAction(DOCACTION_None);
			}
		} else {
			result = false;
		}
		return result;
	}
	
	/**
	 * @return
	 */
	public boolean haveCorrectDocument() {
		boolean result = getReversal_ID() > 0;
		return result;
	}

	public boolean closeIt() {
		log.info(toString());
		// Before Close
		m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_BEFORE_CLOSE);
		if (m_processMsg != null)
			return false;

		setProcessed(true);
		setDocAction(DOCACTION_None);

		// After Close
		m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_AFTER_CLOSE);
		if (m_processMsg != null)
			return false;
		return true;	
	}
	
	/** Reversal Flag		*/
	private boolean m_reversal = false;

	public boolean reverseCorrectIt() {
		boolean result = false;
		log.info(toString());
		if (!haveCorrectDocument()) {
			result = createCorrectDocument();
		}
		return result;
	}
	
	/**
	 * @return
	 */
	private boolean createCorrectDocument() {
		Mhrmintercheckoff reversal = copyFrom (this, getDateFrom(), getDateAcct(), get_TrxName());
		if (reversal == null) {
			m_processMsg = "Could not create Inter CheckOff document Reversal";
			return false;
		}
		reversal.setReversal(true);
		reversal.setName("Canceled -> " + reversal.getName());
		reversal.addDescription("{->" + getDocumentNo() + "}");
		reversal.sethrm_total(gethrm_total().negate());

		Mhrmintercheckoffline[] iLines = reversal.getLinesIntercheckoff();
		for (int i = 0; i < iLines.length; i++)
		{
			Mhrmintercheckoffline iLine = iLines[i];
			iLine.sethrm_amount(iLine.gethrm_amount().negate());
			iLine.saveEx(get_TrxName());
        }
		setProcessed(true);
		
		reversal.setReversal_ID(gethrm_intercheckoff_ID()); 
		reversal.saveEx(get_TrxName());
		if (!reversal.processIt(DocAction.ACTION_Complete))	{
			m_processMsg = "Reversal ERROR: " + reversal.getProcessMsg();
			return false;
		}
		reversal.closeIt();
		reversal.setProcessing (false);
		reversal.setDocStatus(DOCSTATUS_Drafted);
		reversal.setDocAction(DOCACTION_Complete);
		reversal.saveEx(get_TrxName());
		m_processMsg = reversal.getDocumentNo();
		setReversal_ID(reversal.gethrm_intercheckoff_ID());
		addDescription("{" + reversal.getDocumentNo() + "<-}");
		return true;
	}
	
	public static Mhrmintercheckoff copyFrom (Mhrmintercheckoff from, 
			Timestamp dateFrom, 
			Timestamp dateAcct, 
			String trxName) {
		Mhrmintercheckoff to = new Mhrmintercheckoff(from.getCtx(), 0, trxName);
		copyValues(from, to);
		
		to.set_ValueNoCheck (X_hrm_intercheckoff.COLUMNNAME_hrm_intercheckoff_ID, I_ZERO);
		//
		to.setDocStatus (DOCSTATUS_Drafted);		//	Draft
		to.setDocAction(DOCACTION_Complete);
		//
		to.setDateFrom(dateFrom);
		to.setDateAcct (dateAcct);
		//
		to.setIsApproved (false);
		//
		to.setIsTransferred (false);
		to.setPosted (false);
		to.setProcessed (false);
		//[ 1633721 ] Reverse Documents- Processing=Y
		to.setProcessing(false);
		//	delete references
		to.saveEx(trxName);
		
		//	Lines
		// Check lines exist before copy
		if ( from.getLinesIntercheckoff().length > 0 )
		{
		if (to.copyListLinesFrom(from) == 0)
		throw new IllegalStateException("Could not create List");
		}
		
		return to;
	}
	
	public int copyListLinesFrom (Mhrmintercheckoff other) {
		if (isProcessed() || isPosted() || other == null)
			return 0;
		Mhrmintercheckoffline[] fromLines = other.getLinesIntercheckoff();
		int count = 0;
		for (int i = 0; i < fromLines.length; i++)
		{
			Mhrmintercheckoffline line = new Mhrmintercheckoffline (getCtx(), 0, get_TrxName());
			Mhrmintercheckoffline fromLine = fromLines[i];
			PO.copyValues (fromLine, line, fromLine.getAD_Client_ID(), fromLine.getAD_Org_ID());
			line.sethrm_intercheckoff_ID(gethrm_intercheckoff_ID());
			line.set_ValueNoCheck (X_hrm_intercheckoffline.COLUMNNAME_hrm_intercheckoffline_ID, I_ZERO);	// new
			if (line.save(get_TrxName()))
				count++;
		}
		if (fromLines.length != count)
			log.log(Level.SEVERE, "Line difference - From=" + fromLines.length + " <> Saved=" + count);
		return count;
	}
	
	public void addDescription (String description)
	{
		String desc = getDescription();
		if (desc == null)
			setDescription(description);
		else
			setDescription(desc + " | " + description); 
	}	//	addDescription 

	/**
	 * 	Is Reversal
	 *	@return reversal
	 */
	public boolean isReversal()
	{
		return m_reversal;
	}	//	isReversal

	/**
	 * 	Set Reversal
	 *	@param reversal reversal
	 */
	private void setReversal(boolean reversal)
	{
		m_reversal = reversal;
	}	//	setReversal
	
	public boolean reverseAccrualIt() {
		// TODO Auto-generated method stub
		return false;
	}

	public boolean reActivateIt() {
		setDocStatus(STATUS_Drafted);
		setDocAction(DOCACTION_Complete);
		setProcessed(false);
		setPosted(false);
		return true;
	}

	public String getSummary() {
		// TODO Auto-generated method stub
		return null;
	}

	public String getDocumentInfo() {
		// TODO Auto-generated method stub
		return null;
	}

	public File createPDF() {
		// TODO Auto-generated method stub
		return null;
	}

	public String getProcessMsg() {
		// TODO Auto-generated method stub
		return null;
	}

	public int getDoc_User_ID() {
		// TODO Auto-generated method stub
		return 0;
	}
	
	public BigDecimal getApprovalAmt() {
		// TODO Auto-generated method stub
		return null;
	}
	
	public static Mhrmintercheckoff get (Properties ctx, int hrm_intercheckoff_ID)
	{
		Integer key = new Integer (hrm_intercheckoff_ID);
		Mhrmintercheckoff retValue = (Mhrmintercheckoff) s_cache.get (key);
		if (retValue != null)
			return retValue;
		retValue = new Mhrmintercheckoff (ctx, hrm_intercheckoff_ID, null);
		if (retValue.get_ID () != 0)
			s_cache.put (key, retValue);
		return retValue;
	} //	get

	/**	Cache						*/
	private static CCache<Integer,Mhrmintercheckoff>	s_cache	= new CCache<Integer,Mhrmintercheckoff>("hrm_intercheckoff", 20, 2);	//	2 minutes	
	
	// Error message
	private StringBuilder errmsg = new StringBuilder();
	
	/* (non-Javadoc)
	 * @see org.compiere.model.PO#beforeSave(boolean)
	 */
	@Override
	protected boolean beforeSave(boolean newRecord) {
		
		//deduction type
		if(gethrm_deductionType().equals(X_hrm_intercheckoff.HRM_DEDUCTIONTYPE_OTHER)){

			if(getC_ValidCombination_ID()==0) errmsg.append(Util.requiredField(COLUMNNAME_C_ValidCombination_ID)).append("\n");
			Util.checkErrMsg(errmsg);
		}else if(gethrm_deductionType().equals(X_hrm_intercheckoff.HRM_DEDUCTIONTYPE_Prepayment)){
			sethrm_settingsPayments_ID(CalloutInterCheckOff.getSettingsID(X_hrm_intercheckoff.HRM_DEDUCTIONTYPE_Prepayment));
			if(gethrm_settingsPayments_ID()==0) errmsg.append(Util.requiredField(COLUMNNAME_hrm_settingsPayments_ID)).append("\n");
			Util.checkErrMsg(errmsg);
		}
		
		return true;
	}

}
